//
//  GYSStarLevelView.swift
//  星级评价Demo Swift 版
//
//  Created by pcwy2 on 17/2/14.
//  Copyright © 2017年 pcwy2. All rights reserved.
//

import UIKit


/// 属性
class GYSStarLevelView: UIView {

    var kStarFont:Float = 36
    var maxValue:CGFloat = 0;
    var highlightValue:CGFloat = 0;
    var normalColor:UIColor = UIColor()
    var highlightColor:UIColor = UIColor()
    let stars:NSString = "★★★★★"
    
    override func awakeFromNib() {
        super.awakeFromNib()
        setupConfig()
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupConfig()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

/// 函数
extension GYSStarLevelView {
    
    func setupConfig() {
        backgroundColor = UIColor.clear
        normalColor = UIColor.init(red: 237 / 255.0, green: 236 / 255.0, blue: 242 / 255.0, alpha: 1)
        highlightColor = UIColor.orange
    }
    
    func settingMaxValue(max: CGFloat) {
        maxValue = max
    }
    
    func settingHighlightValue(highlight: CGFloat) {
        highlightValue = highlight
        self.setNeedsDisplay()
    }
    func setFontSize(fontSize:Float){
        kStarFont = fontSize
    }
    
    override func draw(_ rect: CGRect) {
        let dictNormal:[String:Any] = [NSFontAttributeName:UIFont.systemFont(ofSize:CGFloat(kStarFont)), NSForegroundColorAttributeName:normalColor]
        let dictHighlight:[String:Any] = [NSFontAttributeName:UIFont.systemFont(ofSize:CGFloat(kStarFont)), NSForegroundColorAttributeName:highlightColor]
        
        let context = UIGraphicsGetCurrentContext()
        var starRect = bounds
        let starSize = stars.size(attributes: dictNormal)
        let Y:CGFloat = (bounds.size.height - starSize.height) / 2.0
        starRect.origin.y = Y
        starRect.size = starSize
        normalColor.set()
        stars.draw(in: starRect, withAttributes: dictNormal)
        
        var clip = starRect
        clip.size.width = clip.size.width * highlightValue / maxValue
        context?.clip(to: clip)
        highlightColor.set()
        stars.draw(in: starRect, withAttributes: dictHighlight)
        
    }
}
